#include "handyFunctions.h"
#include "image.h"

float randomFloat()
{
	return (float)rand() / ((float)RAND_MAX + 1);
}

void explodeName(const char *fileSource, char *fileName, char *filePath)
{
	char file1[64];
	char file2[64] = "";
	strcpy_s(file1, strlen(file1), fileSource);
	file1[strlen(file1) - 4] = '\0';

	int length = (int)strlen(file1);

	int i = length - 1;
	for ( ; i >= 0; --i)
	{
		if (file1[i] == '/' || file1[i] == '\\')
			break;
	}

	if (i != 0)
	{
		++i;
		for (int y = i; y < length; ++y)
			file2[y - i] = file1[y];

		file2[length] = '\0';
		strcpy_s(fileName, strlen(file2), file2);

		memset(file2, '\0', 64);

		--i;
		for(int y = 0; y < i; ++y)
			file2[y] = file1[y];

		file2[i] = '\0';

		strcpy_s(filePath, strlen(file2), file2);
	}
	else
	{
		strcpy_s(fileName, strlen(file1), file1);
	}
}

bool createTexture(UINT &texture, LPSTR fileName)
{
	if (!fileName)
		return false;

	TGAImage *image = NULL;

	if(strstr(fileName, ".jpg"))
	{
		image = loadJPG(fileName);
	}
	else if(strstr(fileName, ".tga"))
	{
		image = loadTGA(fileName);
	}
	else if(strstr(fileName, ".bmp"))
	{
		image = loadBMP(fileName);
	}
	else
		return false;

	if(image == NULL)								
		return false;

	glGenTextures(1, &texture);
	glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
	glBindTexture(GL_TEXTURE_2D, texture);

	// Assume that the texture is a 24 bit RGB texture (convert 16-bit ones to 24-bit)
	int textureType = GL_RGB;

	// If the image is 32-bit (4 channels), then there's a need to specify GL_RGBA for an alpha
	if(image->channels == 4)
		textureType = GL_RGBA;
		
	gluBuild2DMipmaps(GL_TEXTURE_2D, image->channels, image->sizeX, 
					  image->sizeY, textureType, GL_UNSIGNED_BYTE, image->data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	if (image)
	{
		if (image->data)
		{
			free(image->data);
		}

		free(image);
	}

	return true;
}